<template>
  <div>
    <scroller :show-scrollbar="false">
      <vm-cell label="鸡场名称">
        <input slot="title"
               placeholder="请填写鸡场名称"
               v-model="params.farmName"
               class="input" />
      </vm-cell>

      <vm-cell label="联系人">
        <input slot="title"
               placeholder="请填写联系人"
               v-model="params.contact"
               class="input" />
      </vm-cell>

      <vm-cell label="联系电话">
        <input slot="title"
               placeholder="请填写联系电话"
               v-model="params.mobileNo"
               class="input" />
      </vm-cell>

      <vm-cell label="所在地区"
               :has-arrow="true"
               :title="addressCodeName"
               title-align="left"
               placeholder="选择所在地区"
               @cellClicked="pickAddress"></vm-cell>

      <vm-cell label="详细地址">
        <input slot="title"
               placeholder="请填写详细地址"
               v-model="params.addressDetail"
               class="input" />
      </vm-cell>

      <vm-cell label="组织形式"
               :has-arrow="true"
               :title="orgTypeName"
               title-align="left"
               placeholder="选择组织形式"
               @cellClicked="handleOrgType"></vm-cell>

      <vm-cell label="鸡场简介">
        <input slot="title"
               placeholder="请填写鸡场简介"
               v-model="params.des"
               class="input" />
      </vm-cell>

      <vm-cell label="鸡舍数量">
        <text slot="title">{{chickHouse.length}}</text>
        <text>栋</text>
      </vm-cell>

      <div class="flex-row">
        <text class="subtitle">鸡舍</text>
        <text class="subtitle-hint">（最大养殖数/鸡舍视频）</text>
      </div>

      <vm-cell v-for="(house, h) in chickHouse"
               :key="h"
               :label="`    鸡舍${house.house_no}`">
        <text slot="title"
              class="flex">{{house.max_house_scale || '-'}}</text>
        <!-- <input slot="title"
               type="number"
               placeholder="最大养殖数"
               v-model="house.max_house_scale"
               class="input" /> -->
        <div class="house-video-btn"
             @click="showVideo(house, h)">
          <text class="icon house-video-text mr-1">&#xe7da;</text>
          <text class="house-video-text flex">{{house.video_url || '鸡舍视频'}}</text>
        </div>

        <!-- <text class="icon delete-icon"
              v-if="house.deleteEnable"
              @click="deleteHouse(h)">&#xe6d6;</text> -->
      </vm-cell>

      <!-- <div class="m-3 align-right">
        <text class="house-btn icon"
              @click="addHouse">&#xe69f; 添加鸡舍</text>
      </div> -->

    </scroller>

    <div class="bg-white p-1 align-center border-top">
      <vm-button text="提交"
                 size="big"
                 :btn-style="{width: '600px'}"
                 @buttonClicked="sumbit"></vm-button>
    </div>

    <select-address :visible.sync="addressVisible"
                    :address-code="params.farmAddressCode"
                    @select="onAddressSelect"></select-address>

    <wxc-dialog title="提示"
                content="确定删除该鸡舍？"
                :show="deleteHouseShow"
                @wxcDialogCancelBtnClicked="houseDeleteCancel"
                @wxcDialogConfirmBtnClicked="houseDeleteConfirm">
    </wxc-dialog>

    <vm-mask height="400"
             width="560"
             ref="videoMask"
             :top="200"
             :show-close="true"
             :show.sync="videoVisible"
             @close="videoClose">
      <textarea class="textarea"
                ref="videoTextarea"
                v-model="videoUrl"
                rows="8"
                placeholder="填写视频地址"></textarea>
      <text class="textarea-btn"
            @click="onVideoConfirm">确认</text>
    </vm-mask>

  </div>
</template>
<script>
import VmButton from '../../components/vm-button.vue'
import VmCell from '../../components/vm-cell.vue'
import SelectAddress from '../../components/select-address.vue'
import VmMask from '../../components/vm-mask.vue'
import { WxcDialog } from 'weex-ui'
import {
  STORAGE_FARM
} from '../../plugins/constant'
export default {
  components: { VmButton, VmCell, SelectAddress, VmMask, WxcDialog },
  props: {},
  data() {
    return {
      farm: {},
      params: {
        farmName: '',
        contact: '',
        mobileNo: '',
        farmAddressCode: '',
        addressDetail: '',
        des: '',
        chickHouse: 0
      },
      //
      addressVisible: false,
      addressCodeName: '',
      //
      orgType: '',
      orgTypeName: '',
      orgTypeList: [],
      //
      chickHouse: [],
      deleteHouseShow: false,
      deleteHouseIndex: 0,
      //
      videoVisible: false,
      videoUrl: '',
      videoIndex: -1
    }
  },
  computed: {
    typeDialogList() {
      return this.orgTypeList.map(item => item.orgClassName)
    }
  },
  watch: {},
  created() {
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      this.params.farmName = this.farm.farmName
      this.params.contact = this.farm.contact
      this.params.mobileNo = this.farm.mobileNo
      this.params.farmAddressCode = this.farm.farmAddressCode
      this.params.addressDetail = this.farm.addressDetail
      this.params.des = this.farm.des
      this.getAddressCodeName(this.params.farmAddressCode).then(res => {
        this.addressCodeName = res
      })
      this.getOrgType().then(() => {
        for (const type of this.orgTypeList) {
          if (type.orgClass === this.farm.orgClass) {
            this.orgTypeName = type.orgClassName
            break
          }
        }
      })
      this.getChickHouse()
    },
    pickAddress() {
      this.addressVisible = true
    },
    onAddressSelect(id, name) {
      this.params.farmAddressCode = id
      this.addressCodeName = name
    },
    // 鸡舍
    deleteHouse(index) {
      this.deleteHouseIndex = index
      this.deleteHouseShow = true
    },
    houseDeleteCancel() {
      this.deleteHouseShow = false
    },
    houseDeleteConfirm() {
      this.chickHouse.splice(this.deleteHouseIndex, 1)
      this.deleteHouseShow = false
    },
    addHouse() {
      const house_no = this.getMaxHouseNo() + 1
      this.chickHouse.push({
        house_no,
        max_house_scale: '',
        deleteEnable: true
      })
    },
    getMaxHouseNo() {
      let maxNo = 0
      for (const house of this.chickHouse) {
        const hn = +house.house_no || 0
        if (hn > maxNo) { maxNo = hn }
      }
      return maxNo
    },
    // 获取鸡舍
    getChickHouse() {
      this.$notice.loading.show()
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_house',
        params: {
          'supplier_id.eq': this.farm.id
        },
        order: {
          house_no: 'asc'
        }
      }).then(res => {
        this.chickHouse = res || []
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.$notice.loading.hide()
      })
    },
    //
    getAddressCodeName(addressCode) {
      return new Promise((resolve, reject) => {
        if (!addressCode) {
          resolve('')
          return
        }
        this.$http({
          method: 'GET',
          name: 'industrial.geo.address',
          data: { addressCode }
        }).then(res => {
          resolve(res)
        })
      })
    },
    getOrgType() {
      return new Promise((resolve, reject) => {
        this.$http({
          method: 'GET',
          name: 'auth.org.class'
        }).then(res => {
          this.orgTypeList = res || []
          resolve(res)
        })
      })
    },
    handleOrgType() {
      this.$dialog.list({
        items: this.typeDialogList,
        onPositive: ({ position, text }) => {
          this.orgTypeName = text
          const type = this.orgTypeList[position] || {}
          this.orgType = type.orgClass
        }
      })
    },
    // 提交
    sumbit() {
      const chLen = this.chickHouse.length
      if (!chLen) {
        // 删除添加鸡舍功能 @唐文峰
        // return this.$notice.toast({ message: '至少添加一个鸡舍' })
      }
      const formData = { ...this.params }
      formData.farmId = this.farm.id
      formData.chickHouse = chLen
      formData.orgClass = this.orgType
      formData.supplierHouseChickList = []
      for (const ch of this.chickHouse) {
        const maxScale = +ch.max_house_scale || 0
        if (!maxScale) {
          return this.$notice.toast({ message: `请填写鸡舍${ch.house_no}的最大养殖数` })
        }
        formData.supplierHouseChickList.push({
          chickHouseId: ch.chick_house_id || '',
          houseNo: ch.house_no,
          maxHouseScale: ch.max_house_scale,
          videoUrl: ch.video_url,
          supplierId: this.farm.id
        })
      }
      this.$http({
        method: 'PUT',
        name: 'industrial.farm.supplier',
        data: formData,
        errorMsg: '修改失败，请重试'
      }).then(res => {
        this.$notice.toast({ message: '修改成功' })
        this.$router.setBackParams({ type: 1 })
        this.$router.back()
      })
    },
    //
    showVideo(store, index) {
      this.videoIndex = index
      this.videoUrl = store.video_url
      this.videoVisible = true
      setTimeout(() => {
        const ref = this.$refs.videoTextarea
        ref && ref.focus()
      }, 30)
    },
    onVideoConfirm() {
      if (this.videoIndex > -1 && this.videoIndex < this.chickHouse.length) {
        this.chickHouse[this.videoIndex].video_url = this.videoUrl
      }
      this.$refs.videoMask.hide()
      this.videoClose()
    },
    videoClose() {
      this.$tools.resignKeyboard()
    }
  }
}

</script>
<style lang="scss"
       scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.input {
  flex: 1;
  height: 60px;
  font-size: 30px;
  tint-color: #999;
  // text-align: right;
}
.flex-row {
  flex-direction: row;
  align-items: center;
}
.flex {
  flex: 1;
}
.text-center {
  text-align: center;
}
.align-right {
  align-items: right;
}
.align-center {
  align-items: center;
}
.text-muted {
  color: #999;
}
.text-primary {
  color: $primary;
}
.p-1 {
  padding: 10px;
}
.p-3 {
  padding: 30px;
}
.pl-1 {
  padding-left: 10px;
}
.pl-2 {
  padding-left: 20px;
}
.m-3 {
  margin: 30px;
}
.mt-3 {
  margin-top: 30px;
}
.mr-1 {
  margin-right: 10px;
}
.my-3 {
  margin-top: 30px;
  margin-bottom: 30px;
}
.bg-white {
  background-color: #fff;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.border-top {
  border-top-width: 1px;
  border-top-color: $border-color;
}
.align-center {
  align-items: center;
}
.subtitle {
  color: #999;
  padding-top: 30px;
  padding-left: 30px;
  padding-right: 30px;
  padding-bottom: 10px;
}
.subtitle-hint {
  color: #999;
  padding-top: 30px;
  font-size: 24px;
}
.list-text {
  padding: 30px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.list-text-active {
  color: $primary;
}
.delete-icon {
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 20px;
  padding-right: 10px;
  color: $error;
}
.house-btn {
  padding: 20px;
  border-width: 1px;
  border-color: $border-color;
  border-radius: 6px;
  background-color: #fff;
  font-size: 26px;
  width: 200px;
  text-align: center;
  color: $accent;
}

.house-video-btn {
  border-width: 1px;
  border-color: $border-color;
  border-radius: 6px;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 15px;
  padding-right: 15px;
  width: 300px;
  text-align: center;
  flex-direction: row;
  align-items: center;
}
.house-video-text {
  font-size: 26px;
  color: #666;
  overflow: hidden;
  lines: 1;
  height: 30px;
  line-height: 30px;
}

.textarea {
  font-size: 28px;
  color: #333;
  height: 300px;
  padding: 20px;
  border-width: 1px;
  border-color: $border-color;
  tint-color: #999;
}
.textarea-btn {
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
